<template>
  <div class="productSpecification-con">
    <a-space>
      <a-button class="gray-outline" @click="selSpec.visible = true">选择规格</a-button>
      <a-button class="gray-outline" @click="addSpec('add')">新增规格</a-button>
      <a-select :style="{ width: '180px' }" placeholder="选择规格模板" @change="selSpecTem" allow-clear>
        <a-option v-for="item of specTemList" :key="item.id">{{ item.name }}</a-option>
      </a-select>
      <a-button class="gray-outline" @click="setSpecToList">应用</a-button>

      <a-popover trigger="click" v-model:popup-visible="PopupSpecValue">
        <a-button type="text">另存为规格模板</a-button>
        <template #content>
          <div>
            <a-input v-model="specTemName" placeholder="请输入规格模板名称" />
          </div>
          <div class="popup-footer">
            <a-button size="mini" class="gray-outline" @click="PopupSpecValue = false">取消</a-button>
            <a-button size="mini" class="ml10" type="primary" :loading="addSpecLoading" @click="saveSpecTem">确认</a-button>
          </div>
        </template>
      </a-popover>
    </a-space>

    <a-scrollbar style="max-height: 180px; overflow: auto">
      <div v-show="specList[0]" class="sel-con mt10">
        <div class="item clearfix" v-for="(item, index) of specList" :key="index">
          <div class="left fl">
            <div class="sort-icon icon icon-zdp-sort cursor" v-if="specList.length > 1"></div>
            <div class="spec-title-item ml10">
              <div class="pro-div text cursor" @click="addSpec('edit', item)">
                <TextLimit position="top" :rows="1">{{ item.nameCn }}</TextLimit>
              </div>
              <div class="spec-btn pro-div cursor" @click="specList.splice(index, 1)">
                <icon-delete />
              </div>
            </div>
          </div>
          <div class="right fl ml10">
            <!-- <div class="spec-value-con">
              <div class="spec-value-item mr10" v-for="children of item.valueList.filter((e) => e.checked)" :key="children.valueCn">
                <div class="left-text cursor">[{{ children.valueCode }}]{{ children.valueCn }}（{{ children.valueEn }}）</div>
                <div class="btn-del cursor" @click="children.checked = false"><icon-minus-circle /></div>
              </div>
            </div>
            <MyPopoverVue :info="item" @save="addSpecItem" /> -->
            <SpecValueConVue :item="item">
              <MyPopoverVue :info="item" @save="addSpecItem" />
            </SpecValueConVue>
          </div>
        </div>
      </div>
      <a-empty v-show="!specList[0]" description="暂无规格，请先选择规格或者选择规格模板" />
    </a-scrollbar>

    <a-space>
      <a-select placeholder="请选择SKU编码规格" v-model="autoCreateType" :style="{ width: '310px' }">
        <a-option label="SPU-规格值标识（例如：AB0001-R-XL）" value="1"></a-option>
        <a-option label="SPU-自增数字（例如：AB0001-1）" value="2"></a-option>
      </a-select>
      <a-button class="gray-outline" @click="createSku">按规格生成SKU</a-button>
      <a-button class="gray-outline" @click="batchDelTableItem">批量移除</a-button>
    </a-space>

    <a-table v-if="!createLoading" size="mini" class="table-two-line mt10" row-key="onlyKey" :loading="createLoading" :pagination="false" v-model:selectedKeys="selIndexs" :row-selection="{ type: 'checkbox', showCheckedAll: true, width: 40 }" :bordered="{ cell: true }" :scroll="{ y: 240, x: 1160 }" :data="autoCreateList">
      <template #columns>
        <a-table-column title="序号" #cell="{ record, rowIndex }" :width="50">{{ rowIndex + 1 }}</a-table-column>
        <a-table-column title="规格">
          <a-table-column v-for="(item, index) of titleColumnArr" :key="index" :title="item.nameCn" :width="120">
            <template #cell="{ record }">
              {{ record.specValueList.find((e: any) => e.nameCn == item.nameCn).valueCn }}
            </template>
          </a-table-column>
        </a-table-column>
        <a-table-column title="图片" #cell="{ record, rowIndex }" :width="60">
          <UplaodImg :limit="1" v-model="record.skuImg" />
        </a-table-column>
        <a-table-column title="产品SKU" #cell="{ record, rowIndex }" :width="240">
          <a-space style="width: 100%">
            <a-input v-model="record.sku" :style="{ flex: 1 }" :disabled="record.isSelOldSku" />
            <a-button v-if="record.isSelOldSku" size="small" class="gray-outline" @click="restoreItemData(record)">
              <template #icon>
                <icon-close style="font-size: 18px" />
              </template>
            </a-button>
            <a-popover v-model:popup-visible="record.showSetOldSkuPopup" trigger="click">
              <a-button v-if="!record.isSelOldSku" size="small" class="gray-outline">
                <template #icon>
                  <icon-plus style="font-size: 18px" />
                </template>
              </a-button>
              <template #content>
                <a-input-search @search="handleSearch" @press-enter="handleSearch" allow-clear v-model="skuSearchVal" placeholder="请输入sku选择产品" />

                <a-scrollbar style="max-height: 200px; overflow: auto; margin-top: 10px">
                  <div>
                    <a-empty v-if="skuOptions.length <= 0" description="请输入SKU搜索" />
                    <div v-else>
                      <div class="sku-item cursor" @click="selSkuCurIndex = index" :class="[index == selSkuCurIndex ? 'sku_active' : '']" v-for="(item, index) of skuOptions" :key="index">
                        <a-space>
                          <div>
                            <ImgPopover :src="imgUrl(item)">
                              <template #con>
                                <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(item)" />
                              </template>
                            </ImgPopover>
                          </div>
                          <div>
                            <div>{{ item.sku }}</div>
                            <div>{{ $extract(item, 'category.name') }}</div>
                          </div>
                        </a-space>
                      </div>
                    </div>
                  </div>
                </a-scrollbar>

                <div class="popup-footer">
                  <a-button size="mini" class="gray-outline" @click="record.showSetOldSkuPopup = false">取消</a-button>
                  <a-button size="mini" class="ml10" type="primary" @click="setSkuOldValToItem(record)">确认</a-button>
                </div>
              </template>
            </a-popover>
          </a-space>
        </a-table-column>
        <a-table-column title="产品名称" #cell="{ record, rowIndex }" :width="140">
          <a-space>
            <a-input v-model="record.skuName" :disabled="record.isSelOldSku" allow-clear />
            <a-button size="small" class="gray-outline" @click="setGloablePro('skuName', record, rowIndex)">
              <template #icon>
                <icon-double-down />
              </template>
            </a-button>
          </a-space>
        </a-table-column>
        <a-table-column title="重量(g)" #cell="{ record, rowIndex }" :width="140">
          <a-space>
            <a-input-number placeholder="请输入" v-model="record.weightNum" hide-button :disabled="record.isSelOldSku" />
            <a-button size="small" class="gray-outline" @click="setGloablePro('weightNum', record, rowIndex)">
              <template #icon>
                <icon-double-down />
              </template>
            </a-button>
          </a-space>
        </a-table-column>
        <a-table-column title="体积(cm)" #cell="{ record, rowIndex }" :width="240">
          <a-space>
            <a-input-number v-model="record.lengthNum" placeholder="长" hide-button :disabled="record.isSelOldSku" />
            <a-input-number v-model="record.widthNum" placeholder="宽" hide-button :disabled="record.isSelOldSku" />
            <a-input-number v-model="record.heightNum" placeholder="高" hide-button :disabled="record.isSelOldSku" />
            <a-button size="small" class="gray-outline" @click="setGloablePro('volume', record, rowIndex)">
              <template #icon>
                <icon-double-down />
              </template>
            </a-button>
          </a-space>
        </a-table-column>
        <a-table-column title="销售员" #cell="{ record, rowIndex }" :width="200">
          <a-space>
            <a-select class="second" v-model="record.salerIdList" :style="{ width: '140px' }" :max-tag-count="1" allow-search allow-clear multiple placeholder="请选择">
              <a-option :label="item.userName" :value="item.id" v-for="item of userList"></a-option>
            </a-select>
            <a-button size="small" class="gray-outline" @click="setGloablePro('salers', record, rowIndex)">
              <template #icon>
                <icon-double-down />
              </template>
            </a-button>
          </a-space>
        </a-table-column>

        <a-table-column title="采购部门" #cell="{ record, rowIndex }" :width="200">
          <a-space>
            <a-select class="second" @change="deptChange($event, record)" v-model="record.purchaseDeptList[0].id" :style="{ width: '140px' }" :max-tag-count="1" allow-search allow-clear placeholder="请选择">
              <a-option :label="item.deptName" :value="item.id" v-for="item of deptList"></a-option>
            </a-select>
            <a-button size="small" class="gray-outline" @click="setGloablePro('dept', record, rowIndex)">
              <template #icon>
                <icon-double-down />
              </template>
            </a-button>
          </a-space>
        </a-table-column>

        <a-table-column title="操作" :width="60" #cell="{ record, rowIndex }" fixed="right">
          <a-button class="gray-outline" size="mini" @click="autoCreateList.splice(rowIndex, 1)">
            <icon-minus />
          </a-button>
        </a-table-column>
      </template>
    </a-table>
  </div>
  <SelSpec ref="selSpec" @saveSpec="userSelSpecList" :list="specList" />
  <Detail ref="detail" :type="type" :info="info" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, nextTick, onMounted, watch } from 'vue'
  import { pageProductSpecTemplate, saveOrUpdateProductSpecTemplate, getProductSKUList, findDeptList } from '@/api/product'
  import { arraysAreEqual } from '@/utils/index'
  import SelSpec from './selSpec.vue'
  import Detail from '@/views/product/productSetting/specification/components/specificationDetail.vue'
  import { Message } from '@arco-design/web-vue'
  import { getArrayByArrays } from '@/utils'
  import MyPopoverVue from './myPopover.vue'
  import _ from 'lodash-es'
  import Sortable from 'sortablejs'
  import SpecValueConVue from './specValueCon.vue'
  import UplaodImg from '@/components/uploadImg.vue'
  import SkuDetail from '../skuDetail.vue'
  export default defineComponent({
    components: { SelSpec, Detail, MyPopoverVue, SpecValueConVue, UplaodImg },
    props: ['userList', 'formRef', 'spu'],
    setup(props: any, { emit }) {
      const selSpec = ref()
      const detail = ref()
      const data: any = reactive({
        specTemList: [], // 模板列表
        specList: [], // 用户选择的规格项
        type: '',
        info: {},
        specTem: {}, //用户选择的模板，用于应用按钮点击
        PopupSpecValue: false,
        specValueChecked: [],
        autoCreateType: '2', //sku编码规格标识
        autoCreateList: [], //自动生成列表
        selIndexs: [],
        lastCreateSkuList: [], //上一次自动生成的数组
        titleColumnArr: [],
        specTemName: '',
        addSpecLoading: false,
        addOldSkuPopover: false,
        skuListLoading: false,
        skuOptions: [],
        skuSearchVal: '',
        createLoading: false,
        selSkuCurIndex: 0,
        deptList: [],
      })

      const getSpecList = async () => {
        let params = {
          pageSize: 99999,
        }
        const res: any = await pageProductSpecTemplate(params)
        data.specTemList = res?.data?.records || []
      }

      const userSelSpecList = (list: any) => {
        // list.forEach((e: any) => {
        //   let index = data.specList.findIndex((el: any) => el.id == e.id)
        //   if (index == -1) data.specList.push(e)
        // })
        data.specList = list
      }

      const addSpec = (type: string, info?: any) => {
        data.type = type
        data.info = info
        detail.value.visible = true
      }

      const selSpecTem = (val: string) => {
        if (val) {
          data.specTem = data.specTemList.find((e: any) => e.name == val)
        } else {
          data.specTem = {}
        }
      }

      const setSpecToList = () => {
        if (!data.specTem.id) {
          return Message.error('请选择规格模板')
        }
        data.specList = data.specTem.specList
        // let valueList = data.specTem.specList
        // valueList.forEach((e: any) => {
        //   let item: any = data.specList.find((el: any) => e.id == el.id)
        //   if (!item) data.specList.push(e)
        // })
      }

      const addSpecItem = (info: any) => {
        let index = data.specList.findIndex((e: any) => e.id == info.id)
        data.specList[index] = _.cloneDeep(info)
      }

      const rowDrop = () => {
        const body: any = document.querySelector('.sel-con')
        Sortable.create(body, {
          animation: 200, // 定义排序动画的时间
          forceFallback: true,
          sort: true,
          handle: '.sort-icon',
          onEnd(evt: any) {
            data.specList.splice(evt.newIndex, 0, data.specList.splice(evt.oldIndex, 1)[0])
            var newArray = data.specList.slice(0)
            data.specList = []
            nextTick(() => {
              data.specList = newArray
              console.log(data.specList)
            })
          },
        })
      }

      const createSku = async () => {
        const valid: any = await props.formRef.validateField('spu')
        if (valid) return
        let num = 0
        if (!data.specList[0]) {
          return Message.error('请先选择规格')
        }

        data.specList.forEach((e: any) => {
          e.valueList.forEach((el: any) => {
            if (el.checked) num++
          })
        })

        if (num == 0) {
          return Message.error('请至少选择一个规格值之后再生成sku')
        }

        if (!data.autoCreateType) {
          return Message.error('请先选择SKU编码规格')
        }

        data.createLoading = true

        // data.autoCreateList = []
        let arr: any = []
        let curTableData: any = []
        data.specList.forEach((e: any) => {
          e.valueList.map((el: any) => {
            el.nameCn = e.nameCn
            el.nameEn = e.nameEn
            el.specId = e.id
            return e
          })
          let newArr = e.valueList.filter((el: any) => el.checked)
          arr.push(newArr)
        })

        console.log(arr)

        let createArr = getArrayByArrays(arr.filter((e: any) => e.length > 0))
        createArr.forEach((e: any, index: number) => {
          let str = e.map((el: any) => el.valueCode).join('-')
          let obj = {
            onlyKey: index + 1,
            skuImg: '',
            sku: data.autoCreateType == '1' ? `${props.spu}-${str}` : `${props.spu}-${index + 1}`,
            skuName: '',
            specValueList: e,
            weightNum: '',
            heightNum: '',
            lengthNum: '',
            widthNum: '',
            weight: {
              unit: 'g',
              weight: 0,
            },
            volume: {
              height: 0,
              length: 0,
              unit: 'cm',
              width: 0,
            },
            purchaseDeptList: [{ name: '', id: '' }],
            salerIdList: [],
            specFlag: '',
          }
          curTableData.push(obj)
        })

        // 和上一次数据作对比，规格值相同的数据直接填入
        comparisonTableData(curTableData, data.lastCreateSkuList)
        // 重新保存最新的数据，用作对比
        data.lastCreateSkuList = curTableData
        // 每次重新生成表格标题
        data.titleColumnArr = createArr[0]
      }

      // 比对两次数据，相同的加入。不同的追加。最后返回一个数组
      const comparisonTableData = (newArr?: any, oldArr?: any) => {
        let oldData = _.cloneDeep(oldArr)
        newArr.forEach((e: any) => {
          oldData.forEach((el: any) => {
            let arr1 = _.cloneDeep(e.specValueList)
            let arr2 = _.cloneDeep(el?.specValueList || [])
            if (arraysAreEqual(arr1, arr2, 'valueCn')) {
              let newObj = _.cloneDeep(el)
              delete newObj.specValueList
              delete newObj.sku
              e = Object.assign(e, newObj)
            }
          })
        })
        nextTick(() => {
          data.createLoading = false
          data.autoCreateList = newArr
        })
      }

      const saveSpecTem = async () => {
        if (!data.specList[0]) {
          return Message.error('请先选择规格')
        }
        if (!data.specTemName) {
          return Message.error('请输入规格模板名称')
        }
        data.addSpecLoading = true
        try {
          let arr = data.specList.map((e: any) => {
            e.valueList = e.valueList.filter((el: any) => el.checked)
            return e
          })
          let params = {
            name: data.specTemName,
            specList: arr,
          }
          const res: any = await saveOrUpdateProductSpecTemplate([params])
          data.specTemName = ''
          Message.success('保存规格模板成功')
          data.PopupSpecValue = false
        } catch (error) {}
        data.addSpecLoading = false
      }

      const batchDelTableItem = () => {
        if (!data.selIndexs[0]) {
          return Message.error('请勾选需要删除的数据')
        }
        let arr: any = []
        data.autoCreateList.forEach((el: any) => {
          let index = data.selIndexs.findIndex((e: any) => el.onlyKey == e)
          if (index == -1) {
            arr.push(el)
          }
        })
        data.autoCreateList = arr
        data.selIndexs = []
      }

      const handleSearch = async (value: string) => {
        data.selSkuCurIndex = 0
        if (value) {
          try {
            data.skuListLoading = true
            let params = {
              searchType: 'fuzzy',
              keywordType: 'sku',
              keyword: data.skuSearchVal,
            }
            const res: any = await getProductSKUList(params)
            data.skuOptions = res?.data?.records || []
          } catch (error) {}
          data.skuListLoading = false
        } else {
          data.skuOptions = []
        }
      }

      const setSkuOldValToItem = (item: any) => {
        if (!data.skuSearchVal) {
          return (item.showSetOldSkuPopup = false)
        }
        let info: any = data.skuOptions[data.selSkuCurIndex]
        let index = data.autoCreateList.findIndex((e: any) => e.sku == info.sku)
        if (index != -1) return Message.error('sku名称重复，请重新选择')
        let salers = info?.salerList || []
        let picArr = info?.productPicList || []
        if (info) {
          item.isSelOldSku = true
          item.heightNum = info?.volume?.height || ''
          item.widthNum = info?.volume?.width || ''
          item.lengthNum = info?.volume?.length || ''
          item.weightNum = info?.weight?.weight || ''
          item.salerIdList = salers.map((e: any) => e.id)
          item.oldSku = item.sku
          item.sku = info.sku
          item.oldSkuName = item.skuName
          item.skuName = info.skuName
          item.skuImg = picArr[0] ? picArr[0].url : ''
          item.id = info.id
        }
        item.showSetOldSkuPopup = false
        data.skuSearchVal = ''
        data.skuOptions = []
        data.selSkuCurIndex = 0
      }

      const restoreItemData = (item: any) => {
        item.heightNum = ''
        item.widthNum = ''
        item.lengthNum = ''
        item.weightNum = ''
        item.sku = item.oldSku
        item.skuName = item.oldSkuName
        item.salerIdList = []
        item.isSelOldSku = false
      }

      const setGloablePro = (name: string, item: any, index: number) => {
        if (name == 'skuName') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.skuName = item.skuName
            }
          })
        } else if (name == 'weightNum') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.weightNum = item.weightNum
            }
          })
        } else if (name == 'volume') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.heightNum = item.heightNum
              e.widthNum = item.widthNum
              e.lengthNum = item.lengthNum
            }
          })
        } else if (name == 'salers') {
          console.log(item.salerIdList)

          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.salerIdList = item.salerIdList
            }
          })
        } else if (name == 'dept') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.purchaseDeptList[0].id = item.purchaseDeptList[0].id
              e.purchaseDeptList[0].name = item.purchaseDeptList[0].name
            }
          })
        }
      }

      const removeItem = (item: any, i: number) => {
        if (item.id) data.removeProductSkuIdList.push(item.id)
        data.autoCreateList.splice(i, 1)
      }
      const imgUrl = (info: any) => {
        let arr = info?.productPicList || []
        return arr[0] ? arr[0].url : ''
      }

      const getDeptList = async () => {
        const res: any = await findDeptList()
        data.deptList = res?.data || []
      }

      const deptChange = (val: string, info: any) => {
        console.log(val, info)
        let item = data.deptList.find((e: any) => e.id == val)
        if (item) info.purchaseDeptList[0].name = item.deptName
      }

      onMounted(() => {
        rowDrop()
        getDeptList()
      })

      getSpecList()

      return {
        ...(toRefs(data) as any),
        selSpec,
        deptChange,
        userSelSpecList,
        addSpec,
        detail,
        selSpecTem,
        setSpecToList,
        addSpecItem,
        createSku,
        saveSpecTem,
        batchDelTableItem,
        handleSearch,
        setSkuOldValToItem,
        restoreItemData,
        setGloablePro,
        removeItem,
        imgUrl,
      }
    },
  })
</script>

<style lang="less" scoped>
  .sku-item {
    width: 100%;
    height: 50px;
    padding: 5px;
    border: 1px solid #d7d7d7;
    margin-top: 10px;
    border-radius: 5px;
  }

  .sku_active {
    border: 1px solid rgb(var(--primary-6));
  }

  .popup-footer {
    text-align: right;
    margin-top: 5px;
  }

  .productSpecification-con {
    margin: 10px;
  }

  :deep(.arco-scrollbar-type-embed) {
    width: 100%;
  }

  // :deep(.arco-space-item) {
  //   width: 260px;
  // }

  :deep(.arco-upload-list-picture-operation) {
    line-height: 40px;
  }

  :deep(.arco-upload-picture-card) {
    min-width: 40px !important;
    width: 40px !important;
    height: 40px !important;
  }
  :deep(.arco-upload-list-picture) {
    width: 40px !important;
    height: 40px !important;
  }

  // :deep(.arco-popconfirm-icon) {
  //   display: none !important;
  // }

  .sel-con {
    width: 100%;
    // height: 300px;
    // display: flex;
    .item {
      width: 100%;
      // display: flex;
      .left {
        display: flex;
        margin-bottom: 5px;
        .sort-icon {
          width: 30px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          font-size: 24px;
          float: left;
          border: 1px solid #d7d7d7;
          background: #f2f2f2;
        }
        .spec-title-item {
          height: 30px;
          display: flex;
          .pro-div {
            display: inline-block;
            height: 30px;
            box-sizing: border-box;
            border: 1px solid #d7d7d7;
          }
          .text {
            width: 60px;
            padding: 3px 5px;
          }
          .spec-btn {
            height: 30px;
            width: 30px;
            line-height: 30px;
            font-size: 20px;
            text-align: center;
          }
        }
      }
      .right {
        display: flex;
        width: calc(100% - 150px);
        // .spec-value-con {
        //   display: flex;
        //   flex-wrap: wrap;
        //   .spec-value-item {
        //     display: flex;
        //     height: 30px;
        //     line-height: 30px;
        //     border: 1px solid #d7d7d7;
        //     margin-bottom: 5px;
        //     .left-text {
        //       padding: 0 5px;
        //       box-sizing: border-box;
        //       border-right: 1px solid #d7d7d7;
        //     }
        //     .btn-del {
        //       width: 30px;
        //       height: 30px;
        //       text-align: center;
        //       font-size: 20px;
        //     }
        //   }
        // }
      }
    }
  }
</style>
